package com.loe.mvp.ext_view

import android.content.Context
import android.graphics.Color
import androidx.annotation.DrawableRes
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.ImageView
import com.loe.mvp.R
import com.loe.mvp.ext_java.AsyncTimer
import com.loe.mvp.ext_java.timer

/** 加载View */
class LoadingView : FrameLayout
{
    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        initXML(attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        initXML(attrs)
    }

    val imageView = ImageView(context)

    var steep = 12

    var time = 40L

    private var task: AsyncTimer? = null

    private fun initXML(attrs: AttributeSet)
    {
        val array = context.obtainStyledAttributes(attrs, R.styleable.LoadingView)

        setColor(array.getColor(R.styleable.LoadingView_loading_color, Color.WHITE))
        steep = array.getInt(R.styleable.LoadingView_loading_step, steep)
        time = array.getInt(R.styleable.LoadingView_loading_time, time.toInt()).toLong()

        imageView.setImageResource(R.drawable.icon_loading)
        val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
//        val margin = px(10)
//        params.setMargins(margin, margin, margin, margin)
        addView(imageView, params)

        imageView.rotationX = 0.5f
        imageView.rotationY = 0.5f

        var i = 0
        task = timer(0, time)
        {
            imageView.rotation = 360f / steep * i++
            if (i >= steep) i = 0
        }

//        val animation = RotateAnimation(
//            0f, 360f,
//            Animation.RELATIVE_TO_SELF, 0.5f,
//            Animation.RELATIVE_TO_SELF, 0.5f
//        ).apply {
//
//            duration = 800
//            repeatCount = Integer.MAX_VALUE
//            interpolator = LinearInterpolator()
//            fillAfter = true
//        }
//        imageView.startAnimation(animation)

        array.recycle()
    }

    fun setImageResource(@DrawableRes resId: Int)
    {
        imageView.setImageResource(resId)
    }

    fun setColor(color: Int)
    {
        imageView.setColorFilter(color)
    }

    override fun onDetachedFromWindow()
    {
        task?.stop()
        super.onDetachedFromWindow()
    }
}